package MyArrayList;

import java.util.Arrays;

public class MyArray implements List {
    public int[] elem;
    public int size;

    public MyArray() {
        this.elem = new int[10];
    }

    // 新增元素,默认在数组最后新增
    public void add(int data) {
        if (isFull()) {
            grow();
        }

        elem[size] = data;
        size++;
    }

    public boolean isFull() {
        return size == elem.length;
    }

    public void grow() {
        elem = Arrays.copyOf(elem, 2 * elem.length);
    }


    @Override
    public void add(int pos, int data) {
        if (pos < 0 || pos > size) {
            throw new PosOutOfException("pos位置不合法");
        }
        if (isFull()) {
            grow();
        }
        for (int i = size; i > pos; i--) {
            elem[i] = elem[i - 1];
        }
        elem[pos] = data;
        size++;
    }

    @Override
    public boolean contains(int toFind) {
        if (isEmpty()) {
            throw new PosOutOfException("数组为空");
        }

        for (int i = 0; i < size; i++) {
            if (elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    // 查找某个元素对应的位置
    @Override
    public int indexOf(int toFind) {
        if (isEmpty()) {
            throw new PosOutOfException("数组为空");
        }
        for (int i = 0; i < size; i++) {
            if (elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    // 获取 pos 位置的元素
    @Override
    public int get(int pos) {
        if (pos < 0 || pos > size) {
            throw new PosOutOfException("pos位置不合法");
        }
        if (isEmpty()) {
            throw new PosOutOfException("elem为空");
        }
        return elem[pos];
    }

    // 给 pos 位置的元素设为 value
    @Override
    public void set(int pos, int value) {
        if (pos < 0 || pos > size) {
            throw new PosOutOfException("pos位置不合法");
        }
        if (isEmpty()) {
            throw new PosOutOfException("elem为空");
        }
        elem[pos] = value;
    }

    //删除第一次出现的关键字key
    //调用Index来获取我们需要删除的下标数据
    @Override
    public void remove(int toRemove) {
        int key = indexOf(toRemove);
        if (key == -1) {
            return;
        }
        for (int i = key; i < size - 1; i++) {
            elem[i ] = elem[i+1];
        }
        size--;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void clear() {
        size = 0;
    }

    // 打印顺序表，注意：该方法并不是顺序表中的方法，为了方便看测试结果给出的
    @Override
    public void display() {
        for (int i = 0; i < size; i++) {
            System.out.println(get(i)+" ");
        }
        System.out.println();
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

}
